package org.ns.summer.mvc.mappinghandler;

import org.ns.summer.beans.anns.Component;
import org.ns.summer.core.AnnotationUtils;
import org.ns.summer.core.BeanUtils;
import org.ns.summer.mvc.anns.RequestParam;
import org.ns.summer.mvc.dynamicexec.ExecParamInfo;
import org.ns.summer.mvc.dynamicexec.ExecParamTemplate;
import org.ns.summer.mvc.error.ParamRequiredException;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

//@Component  这个作为默认的实现直接配置，不在这里标记 @Component
public class ParamAnnotationTemplate implements ExecParamTemplate {
    @Override
    public Object paramLoad(ExecParamInfo autoParamInfo) throws Exception{
        HttpServletRequest request = (HttpServletRequest) autoParamInfo.getAutoParam().get(HttpServletRequest.class);
        RequestParam requestParam = AnnotationUtils.getAnnotation(autoParamInfo.getAnnotations(), RequestParam.class);
        Class<?> paramType = autoParamInfo.getParamType();
        String name = requestParam.value();
        String value = request.getParameter(name);

        if (requestParam.required() && (value == null || value.isEmpty())) {
            throw new ParamRequiredException(name);
        }

        return BeanUtils.getValue(value, paramType, (t, v)-> {
            if (paramType == Date.class) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(requestParam.timeformat());
                return simpleDateFormat.parse(value);
            }
            return null;
        });

    }

    @Override
    public boolean preHandle(ExecParamInfo autoParamInfo) {
        return AnnotationUtils.existSuperAnnotation(autoParamInfo.getAnnotations(), RequestParam.class);
    }
}
